import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Drawer, Form, FormProps, Input, Space } from 'antd';

import { store } from '@/store';

import { permissionApiSyncPageAndApi } from '@/services/base/quanxianmokuaihouduanjiekouxinxijiekou';

export type GenJsonRef = {
  open: (arg: { onSuccess: () => void }) => void;
};

export type GenJsonProps = {};

const GenJson: React.ForwardRefRenderFunction<GenJsonRef, GenJsonProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<GenJsonRef['open']>[0]>();
  const submit = useRequest(
    async (values) => {
      const res = await permissionApiSyncPageAndApi(values);

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(res.message || '操作成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(async () => {
          form.resetFields();
          form.setFieldsValue({});
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values.data);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title="生成权限"
      extra={
        <Space>
          <Button
            type="primary"
            loading={submit.loading}
            disabled={submit.loading}
            onClick={onSave}
          >
            保存
          </Button>
          <Button onClick={onCancel} disabled={submit.loading}>
            取消
          </Button>
        </Space>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form onFinish={onFinish} form={form}>
        <Form.Item
          name="data"
          label="菜单json"
          rules={[{ required: true, message: '请输入需要生成权限的页面' }]}
        >
          <Input.TextArea
            placeholder="请输入需要生成权限的页面"
            autoSize={{ minRows: 10, maxRows: 20 }}
          />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(GenJson);
